#include <stdio.h>
#include <stdlib.h>

#include <mpv/client.h>

#include "libmpv.h"

mpv_handle *ctx;

static int
check_error(int status)
{
	if (status < 0) {
		fprintf(stderr, "mpv API error: %s\n", mpv_error_string(status));
	}

	return status;
}

int
libmpv_init(void)
{
	int val;

	ctx = mpv_create();
	if (!ctx) {
		fprintf(stderr, "failed creating context\n");
		return 1;
	}

	check_error(mpv_set_option_string(ctx, "include", "~/.config/mpvd/mpv.conf"));
	check_error(mpv_set_option_string(ctx, "input-conf", "~/.config/mpvd/input.conf"));

	val = 1;
	check_error(mpv_set_option(ctx, "osc", MPV_FORMAT_FLAG, &val));

	/* Done setting up options. */
	check_error(mpv_initialize(ctx));

	return 0;
}

int
libmpv_play(char *file)
{
	const char *cmd[] = {"loadfile", file, NULL};

	return check_error(mpv_command(ctx, cmd));
}

int
libmpv_queue(char *file)
{
	const char *cmd[] = {"loadfile", file, "append-play", NULL};

	return check_error(mpv_command(ctx, cmd));
}

int
libmpv_next(void)
{
	const char *cmd[] = {"playlist-next", NULL};

	return check_error(mpv_command(ctx, cmd));
}

int
libmpv_prev(void)
{
	const char *cmd[] = {"playlist-prev", NULL};

	return check_error(mpv_command(ctx, cmd));
}

int
libmpv_stop(void)
{
	const char *cmd[] = {"stop", NULL};

	return check_error(mpv_command(ctx, cmd));
}

int
libmpv_keypress(char *key)
{
	const char *cmd[] = {"keypress", key, NULL};

	return check_error(mpv_command(ctx, cmd));
}

int
libmpv_event_file_loaded(void)
{
	char *prop = NULL;
	int ret;

	/* FIXME this, and check_error(), is fucking shit. */
	ret = mpv_get_property(ctx, "path", MPV_FORMAT_STRING, &prop);
	if (0 < ret) {
		return check_error(ret);
	}

	printf("%s\n", prop);
	mpv_free(prop);

	return ret;
}
